from myapp import models
from myapp.utils.form import LoginForm
from django.shortcuts import render,redirect,HttpResponse
from myapp.utils.code import check_code


def login(request):
    """登录功能"""
    if request.method=="GET":
        form = LoginForm
        return  render(request,'login.html',{'form':form})
    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 做一个验证码校验
        img_code = request.session.get('img_code','') # 取出session中的验证码
        user_code = form.cleaned_data.pop('code')# 用pop取出存在cleaned_data中的验证码并清除，不然会影响下方的登录账号密码查询
        if user_code.upper() != img_code.upper(): # 优先进行验证码比对
            form.add_error("code",'验证码错误')
            return render(request, 'login.html', {'form': form})
        # 下方为登录账号密码验证
        admin_obj = models.Admin.objects.filter(**form.cleaned_data).first() #form.cleaned_data为字典{'username': 'ayerjo', 'password': '202cb96...'}
        if not admin_obj:
            form.add_error("password", "用户名或密码错误")
            return render(request, 'login.html', {'form': form})
        request.session['info'] = {'id':admin_obj.id,'username':admin_obj.username,'password':admin_obj.password} #存session进数据库
        request.session.set_expiry( 60 * 60 * 24 )#重新设置session为1天
        return redirect('/admin/list/')
    return render(request, 'login.html', {'form': form})


def img_code(request):
    """生成图片验证码"""
    img,code_str = check_code()#使用封装好的验证码类
    request.session['img_code'] = code_str # 将验证码存入session,用于登录取出校验
    request.session.set_expiry(60) # 设置session时间为60秒，用于验证码60秒失效
    # 3. 将图片写入内存(Python3)
    from io import BytesIO
    stream = BytesIO() #
    img.save(stream, 'png')#这里是将图片存入stream对象，stream.getvalue()是获取stream里存的图片
    return HttpResponse(stream.getvalue())

def loginout(request):
    """注销功能"""
    request.session.clear()
    return redirect('/login/')